<template>
  <el-dialog append-to-body class="common_dialog" custom-class="reset-dialog-width" :visible.sync="visible" title='请选择经纬度' :close-on-click-modal="false" :close-on-press-escape="false">
    <!-- 高德地图 -->
    <div v-if="visible" id="container"></div>
    <!-- 搜索 -->
    <div id="search">
      <el-input v-model="searchValue" placeholder="请输入要搜索的位置" clearable @keyup.enter.native="seachAddress" />
      <el-button type="primary" icon="el-icon-search" size="mini" @click="seachAddress">搜索</el-button>
    </div>
    <template slot="footer">
      <el-button :loading="confirmLoading" type="primary" @click="submitHandle()">确 定</el-button>
      <el-button @click="visible = false">取 消</el-button>
    </template>
  </el-dialog>
</template>

<script>

export default {
  name: "ChooseAddress",
  props: {

  },
  data() {
    return {
      visible: false,
      confirmLoading: false,
      searchValue: '',
      gdmap: null,
      geoCoder: null,
      /* 当前位置 */
      thisPosition: {
        location: '',
        lng: '',
        lat: ''
      },
      /* 选取的位置 */
      chosePosition: {
        location: '',
        lng: '',
        lat: ''
      },
      positionPickerObj: {},
      /* 当前城市编码 */
      citycode: '0335',
      //标记
      marker: [],
      centerMarker: null, //初始化地图中心点
      address: ''
    }
  },
  created() {

  },
  methods: {
    init() {
      this.visible = true
      this.searchValue = ''
      this.$nextTick(() => {
        //地图初始化
        this.gdmap = new AMap.Map('container', {
          resizeEnable: true,//是否监控地图容器尺寸变化
          zoom: 15,//地图显示的缩放级别
          zooms: [3, 18],//地图显示的缩放级别范围在PC上，默认为[3,18]，取值范围[3-18]；
          viewMode: '2D',//默认为‘2D’，可选’3D’，选择‘3D’会显示 3D 地图效果
          center: this.centerMarker, // 初始化地图中心点位置
        })
        this.confirmLoading = false
        //加载工具条
        this.addTool();
        //获取当前位置
        this.thisLocation();
      })
    },
    //工具条
    addTool() {
      AMap.plugin(['AMap.ToolBar'], () => {
        let toolbar = new AMap.ToolBar()
        this.gdmap.addControl(toolbar)
      })
    },
    //定位
    thisLocation() {
      AMap.plugin("AMap.Geocoder", () => {
        this.geoCoder = new AMap.Geocoder({
          radius: 1000,
        });
      })
      this.positionPicker();
    },
    onMapclick(e) {
      this.chosePosition = [e.lnglat.lng, e.lnglat.lat]
      this.relocation(e.lnglat);
    },
    relocation(lnglat, addr) {
      let lng = lnglat.lng;
      let lat = lnglat.lat;
      var self = this;
      this.gdmap.panTo([lng, lat]);
      this.positionPickerObj.start(addr ? null : lnglat)
      if (addr) {
        var label = '<div class="info">地址:' + addr + '<br>经度:' + lng + '<br>纬度:' + lat + '</div>';
        self.positionPickerObj.marker.setLabel({
          offset: [10, 10],
          content: label //显示内容
        });
      } else {
        this.geoCoder.getAddress(lng + ',' + lat, function (status, result) {
          if (status === 'complete' && result.regeocode) {
            var address = result.regeocode.formattedAddress;
            var label = '<div class="info">地址:' + address + '<br>经度:' + lng + '<br>纬度:' + lat + '</div>';
            self.positionPickerObj.marker.setLabel({
              offset: [10, 10],
              content: label //显示内容
            });
          } else {
            // console.log(JSON.stringify(result));
          }
        });
      }
    },
    /* 拖拽选址 */
    positionPicker() {
      AMapUI.loadUI(['misc/PositionPicker'], (PositionPicker) => {
        this.positionPickerObj = new PositionPicker({
          mode: 'dragMarker', // 设定为拖拽地图模式，可选'dragMap'、'dragMarker'，默认为'dragMap'
          map: this.gdmap // 依赖地图对象
        })
        this.positionPickerObj.on('success', (positionResult) => {
          this.chosePosition = positionResult.position;
          this.address = positionResult.address;
          var label = '<div class="info">地址:' + positionResult.address + '<br>经度:' + positionResult.position.lng + '<br>纬度:' + positionResult.position.lat + '</div>';
          this.positionPickerObj.marker.setLabel({
            offset: [10, 10],
            content: label //显示内容
          });
        })
        if (this.chosePosition.lng) {
          this.relocation(this.chosePosition, this.address);
        } else {
          let initPosition = {}
          initPosition.lng = this.centerMarker[0]
          initPosition.lat = this.centerMarker[1]
          this.chosePosition = initPosition;
          this.relocation(initPosition, this.address);
        }
        this.gdmap.on('click', this.onMapclick);
      })
    },
    //搜索
    seachAddress() {
      if (this.searchValue != '') {
        //清楚地图上的覆盖物
        this.gdmap.clearMap();
        this.gdmap.plugin('AMap.PlaceSearch', () => {
          let placeSearch = new AMap.PlaceSearch({
            // city 指定搜索所在城市，支持传入格式有：城市名、citycode和adcode
            city: '0335',
            map: this.gdmap
          });
          let that = this;
          placeSearch.search(this.searchValue, function (status, result) {
            // 查询成功时，result即对应匹配的POI信息
            var pois = result.poiList.pois;
            for (var i = 0; i < pois.length; i++) {
              var poi = pois[i];
              var marker = [];
              marker[i] = new AMap.Marker({
                position: poi.location,   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                title: poi.name
              });
              // 将创建的点标记添加到已有的地图实例：
              that.gdmap.add(marker[i]);
            }
            that.gdmap.setFitView();
            AMap.Event.addListener(placeSearch, 'markerClick', function (data) {
              that.relocation(data.data.location);
            })

          });
        })
      }
    },
    submitHandle() {
      this.visible = false
      this.confirmLoading = true
      this.$emit('refreshAddressPosition', this.chosePosition, this.address)
    }
  }
};
</script>
<style lang="scss" scoped>
.common_dialog {
  .amap-marker-label {
    padding: 0.75rem 1.25rem;
    margin-bottom: 1rem;
    border-radius: 0.25rem;
    position: fixed;
    top: 2rem;
    background-color: white;
    width: auto;
    min-width: 22rem;
    border-width: 0;
    left: 1.8rem;
    box-shadow: 0 2px 6px 0 rgba(114, 124, 245, 0.5);
  }
}
#container {
  width: 100%;
  height: 550px;
  z-index: 1;
}
#search {
  z-index: 999;
  position: absolute;
  top: 46px;
  opacity: 1;
  display: flex;
}
</style>
